from django.shortcuts import HttpResponse
import cmdb.api.http_result as hh
from cmdb import models
import uuid
from cmdb.util import time
from django.conf import settings
from cmdb.util import http_util as hu
from cmdb.util.string_number import StringNumber
from django.db import transaction
from cmdb.util.random_util import random_divider
from cmdb.api.session import session_set
from cmdb.api.session import session_get


# 发红包
#   往redpacket中添加红包记录  status: 0
#   往redpacketsub 中添加子红包
#   添加失败后事务回滚
# 事务回滚
@transaction.atomic
def send_packet(req):
    dd = hu.json_obj(req)
    data = dd[0]
    token = req.POST.get('token', '')
    if data:
        user_id = session_get(token, 'user_id')
        if user_id:
            game_id = data.get('game_id', None)
            if not game_id:
                return hh.resp_result(0, 'game_id is null')
            grade = data.get('grade', 0)
            num = data.get('num', 1)
            money = data.get('money', 0)
            if money == 0:
                return hh.resp_result(0, 'money is too little')

            invalid_time = data.get('invalid_time', 0)
            if invalid_time == 0:
                return hh.resp_result(0, 'invalid_time is null')

            packet_id = gen_packet_id()

            # 添加红包
            pid = uuid.uuid1()
            try:
                models.RedPacket.objects.create(id=pid, packet_id=packet_id, game_id=game_id, grade=grade, num=num,
                                                user_id= user_id, money=money, invalid_time=invalid_time,
                                                timestamp=time.current_timestamp())

                # 生成子红包的金额 随机
                sub_money = random_divider(money, num)
                # print(sub_money)
                # 保存子红包
                for m in sub_money:
                    sp_id = uuid.uuid1()
                    models.RedPacketSub.objects.create(id=sp_id, packet_id=packet_id, money=m)
            except BaseException as e:
                print(e)
                return hh.resp_result(0, hh.DELETE_ERROR, {hh.ERROR_INFO: e.__str__()})
            else:
                return hh.resp_result(1, hh.RESULT_SUCCESS, {'packet_id': packet_id})

        else:
            return hh.resp_result(0, 'user_id lost, please login again')

    else:
        return hh.resp_result(0, hh.RESULT_FAIL, {'error_info': dd[1]})


# 生成红包的编码  用户可以看到, 用来分享  发送给好友等
def gen_packet_id():
    rs = models.PacketCode.objects.all().order_by('-id')[:1]

    code = 'A01'
    if rs.__len__() == 1:
        code = rs[0].code
        sn = StringNumber()
        sn.set_str_value(code)
        sn.add_one()
        code = sn.str_value()

    # 更新数据库
    models.PacketCode.objects.create(code=code)

    return code


# 删除红包记录
#   删除redpacket 表中的记录
#   删除redpacketsub 表中的记录
#   删除失败后事务回滚
# 事务回滚
@transaction.atomic
def delete(req):

    data = hu.json_obj(req)[0]
    packet_id = ''
    token = req.POST.get('token', '')
    if data:
        packet_id = data.get('packet_id', None)
        if not packet_id:
            return hh.resp_result(0, 'packet_id is null')

    # 删除红包
    user_id = session_get(token, 'user_id')
    try:
        p = models.RedPacket.objects.get(packet_id=packet_id, user_id=user_id)
        p.delete()

        rs = models.RedPacketSub.objects.filter(packet_id=packet_id)
        for pp in rs:
            pp.delete()

    except BaseException as e:
        return hh.resp_result(0, 'An error occurred while deleting the table', {hh.ERROR_INFO: e.__str__()})
    else:
        return hh.resp_result(1, hh.RESULT_SUCCESS)


# 领取红包
#   查询红包关联的游戏的信息, 游戏名称, 游戏ID等
def get_packet(req):
    data = hu.json_obj(req)[0]
    if data:
        packet_id = data.get('packet_id', None)
        if packet_id:
            try:
                p = models.RedPacket.objects.get(packet_id=packet_id)
                if p.status == 0:
                    return hh.resp_result(0, 'the packet is not available yet')
                elif p.status == 2:
                    return hh.resp_result(0, 'the packet is timeout')

                game_id = p.game_id
                game = models.Game.objects.get(id=game_id)
                if game.status == 0:
                    return hh.resp_result(0, 'the game of the packet is not available')

                status = 0
                # 查询红包是否被领取完了
                rs = models.RedPacketSub.objects.filter(packet_id=packet_id, user_id='')
                if len(rs):
                    status = 1
                return hh.resp_result(1, hh.RESULT_SUCCESS, {'game_id': game_id, 'name': game.name, 'status': status})


            except BaseException as e:
                return hh.resp_result(0, hh.RESULT_FAIL, {hh.ERROR_INFO: e.__str__()})

        else:
            return hh.resp_result(0, 'packet_id is null')
    else:
        return hh.resp_result(0, hh.PARAMETER_ERROR)


# 抢红包
#   查询红包状态 为1(正常) 时OK
@transaction.atomic
def grab_packet(req):
    data = hu.json_obj(req)[0]
    token = req.POST.get('token', '')
    if data:
        packet_id = data.get('packet_id', None)
        if packet_id:
            p = models.RedPacket.objects.get(packet_id=packet_id)
            if p.status == 1:
                rs = models.RedPacketSub.objects.filter(packet_id=packet_id, user_id='').select_for_update()

                if len(rs) > 0:
                    user_id = session_get(token, 'user_id')
                    if user_id:
                        for rp in rs:
                            rp.user_id = user_id
                            rp.timestamp = time.current_timestamp()
                            try:
                                rp.save()
                            except BaseException as e:
                                return hh.resp_result(0, hh.RESULT_FAIL, {hh.ERROR_INFO: e.__str__()})
                            else:
                                return hh.resp_result(1, hh.RESULT_SUCCESS, {'money': rp.money})
                    else:
                        return hh.resp_result(0, 'user_id is null')
                else:
                    return hh.resp_result(0, 'the packet is grab finished')
            else:
                if p.status == 0:
                    return hh.resp_result(0, 'the packet is not available yet')
                else:
                    return hh.resp_result(0, 'the packet is timeout')
        else:
            return hh.resp_result(0, 'packet_id is null')
    else:
        return hh.resp_result(0, hh.PARAMETER_ERROR)



# 获取我已经发的红包
def get_my_send_packet(req):
    token = req.POST.get('token', '')
    user_id = session_get(token, 'user_id')
    if user_id:
        rs = models.RedPacket.objects.filter(user_id=user_id)
        results = []
        for p in rs:
            packet_id = p.packet_id
            rss = models.RedPacketSub.objects.filter(packet_id=packet_id, user_id='')
            residue = len(rss)
            if residue < 0:
                return hh.resp_result(0, 'packet is error with the wrong sub packet')
            else:
                try:
                    game = models.Game.objects.get(id=p.game_id)

                    results.append({
                        'packet_id': p.packet_id,
                        'game_id': p.game_id,
                        'game_icon': game.icon,
                        'game_image': game.image,
                        'timestamp': p.timestamp,
                        'num': p.num,
                        'residue': residue,
                        'grade': p.grade,
                        'status': p.status
                    })

                except BaseException as e:
                    return hh.resp_result(0, 'the game of the packet is not exist', {hh.ERROR_INFO: e.__str__()})

        return hh.resp_result(1, hh.RESULT_SUCCESS, results)

    else:
        return hh.resp_result(0, 'user_id is null, please login again.')



# 获取红包领取详情
#   返回领取改红包的用户ID, 名字等信息
def get_packet_grab_detail(req):
    data = hu.json_obj(req)[0]
    if data:
        packet_id = data.get('packet_id', None)
        if packet_id:
            rs = models.RedPacketSub.objects.filter(packet_id=packet_id).extra(where=['user_id != ""'])
            results = []
            for p in rs:
                results.append({
                    'user_id': p.user_id,
                    'name': p.user.name,
                    'head': p.user.head,
                    'money': p.money,
                    'timestamp': p.timestamp,
                })

            return hh.resp_result(1, hh.RESULT_SUCCESS, results)

        else:
            return hh.resp_result(0, 'packet_id is null')
    else:
        return hh.resp_result(0, hh.PARAMETER_ERROR)